package forms;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import entities.Pais;

import java.awt.Component;
import java.util.List;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class Main {

	private JFrame frame;
	private JTextField txtPais;
	private JTable table;
	private JScrollPane scrollPane;

	private static SessionFactory factory;
	private static Session session;
	private JTextArea textArea;
	private JScrollPane scrollPane_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Main window = new Main();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Main() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(400, 200, 972, 729);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		JButton btnNewButton = new JButton("listar");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				listar();
			}
		});
		btnNewButton.setBounds(127, 5, 89, 23);
		frame.getContentPane().add(btnNewButton);

		txtPais = new JTextField();
		txtPais.setBounds(226, 40, 86, 20);
		txtPais.setHorizontalAlignment(SwingConstants.CENTER);
		frame.getContentPane().add(txtPais);
		txtPais.setColumns(10);

		// DefaultTableModel model = new DefaultTableModel();
		// model.setColumnIdentifiers(new String[] { "a", "b", "c", "d" });
		// model.setRowCount(20);

		table = new JTable();
		// table.setModel(model);

		scrollPane = new JScrollPane();
		scrollPane.setBounds(72, 90, 452, 169);
		scrollPane.setViewportView(table);

		frame.getContentPane().add(scrollPane);

		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

		JButton btnInsertar = new JButton("insertar");
		btnInsertar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				insertar(txtPais.getText());
			}
		});
		btnInsertar.setBounds(127, 39, 89, 23);
		frame.getContentPane().add(btnInsertar);

		scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(30, 270, 900, 300);
		frame.getContentPane().add(scrollPane_1);

		textArea = new JTextArea();
		textArea.setWrapStyleWord(true);
		scrollPane_1.setViewportView(textArea);

		frame.getContentPane().setFocusTraversalPolicy(
				new FocusTraversalOnArray(new Component[] { txtPais,
						btnNewButton }));
	}

	private void listar() {
		try {
			textArea.setText(textArea.getText() + "\n" + "comenzo factory");
			factory = new Configuration().configure("config/hibernate.cfg.xml")
					.buildSessionFactory();
			textArea.setText(textArea.getText() + "\n" + "termino factory --- " + factory.toString());
			
		} catch (Throwable ex) {

			textArea.setText(textArea.getText() + "\n"
					+ "Failed to create sessionFactory object." + ex);
			// System.err.println("Failed to create sessionFactory object." +
			// ex);
			throw new ExceptionInInitializerError(ex);
		}

		try {
			textArea.setText(textArea.getText() + "\n" + "comenzo session");
			session = factory.openSession();
			textArea.setText(textArea.getText() + "\n" + "termino session");
			Query q = session.createQuery("from " + Pais.class.getName());
			textArea.setText(textArea.getText() + "\n" + "termino query");
			List l = q.list();
			textArea.setText(textArea.getText() + "\n" + "termino list()");
			displayResult(l);
			textArea.setText(textArea.getText() + "\n"
					+ "termino displayresutl");
		} catch (Throwable ex) {
			textArea.setText(textArea.getText() + "\nmessage"
					+ ex.getMessage());
			textArea.setText(textArea.getText() + "\nlocalized"
					+ ex.getLocalizedMessage());
			for(StackTraceElement o : ex.getStackTrace() ){
				textArea.setText(textArea.getText() + "\n"
						+ o.toString());	
				
			}
			
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	private void insertar(String pais) {
		try {
			factory = new Configuration().configure("config/hibernate.cfg.xml")
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}

		try {
			session = factory.openSession();
			Transaction tx = session.beginTransaction();
			try {
				Pais p = new Pais();
				p.setNombre2(pais);
				session.save(p);

				tx.commit();
				tx = null;
			} finally {
				if (tx != null) {
					tx.rollback();
					tx = null;
				}
			}
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}

	private void displayResult(List resultList) {
		Vector<String> tableHeaders = new Vector<String>();
		Vector tableData = new Vector();
		tableHeaders.add("Id pais");
		tableHeaders.add("Nombre");

		for (Object o : resultList) {
			Pais p = (Pais) o;
			Vector<Object> oneRow = new Vector<Object>();
			oneRow.add(p.getId());
			oneRow.add(p.getNombre2());
			tableData.add(oneRow);
		}
		table.setModel(new DefaultTableModel(tableData, tableHeaders));
	}
}
